package com.atjava.nebula.weixin.ssl;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.atjava.nebula.core.exception.baseExp.BusinessException;
import com.atjava.nebula.web.ssl.HttpsClient;

/**
 * 
 * @author jindong
 *
 */
public class WeixinHttpsApiCaller {
	
	private static String CORP_ID = "wx0a1da01be66bb6c2";
	private static String CORP_SECRET = "gNCFmXCSvkyR58pFd5rXSfNt07oGmoYwTtw5sh61Wro82Kc58CHK9_ut_VS3DEN4";
	private static String AGENT_ID = "1";
	
	private static final String JSONKEY_ERROR_CODE = "errcode";
	private static final String JSONKEY_ERROR_MSG = "errmsg";
	private static final String JSONKEY_ACCESS_TOKEN = "access_token";
	private static final String JSONKEY_TOKEN_EXPIRES = "expires_in";
	private static final String JSONKEY_USERID = "UserId";
	
	private static Lock lock = new ReentrantLock();
	private static String _accessToken;
	private static long _expiresIn;
	private static Timer timer = new Timer();;
	
	public static String getAccessToken() throws BusinessException{
		
		lock.lock();
		try {
			if(_accessToken == null){

					HttpsClient client = new HttpsClient();
					String json = client.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken"
							+ "?corpid=" + CORP_ID
							+ "&corpsecret=" + CORP_SECRET);
					_accessToken = getValueFromJson(json, JSONKEY_ACCESS_TOKEN);
					_expiresIn = Long.parseLong(getValueFromJson(json, JSONKEY_TOKEN_EXPIRES));
					timer.schedule(new TimerTask() {
						public void run() {
							lock.lock();
							_accessToken = null;
							lock.unlock();
						}
					}, (_expiresIn-20)*1000);
				
			}
			return _accessToken;
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			throw new BusinessException(e,"连接微信服务器失败！");
		} finally{
			lock.unlock();
		}
		
	}
	
	
	private static String getValueFromJson(String json,String key) throws BusinessException{
		
		JSONObject result = JSONObject.fromObject(json);
		String value = null;
		try{
			value = result.getString(key);
		}catch(JSONException e){
			String errorCode = result.getString(JSONKEY_ERROR_CODE);
			String errorMsg = errorCode + ":" + result.getString(JSONKEY_ERROR_MSG);
			throw new BusinessException("从微信服务器获取["+key+"]失败！["+errorMsg+"]");
		}
		return value;
	}
	
	public static String getUserId(String code) throws BusinessException{
		
		try {
			String accessToken = getAccessToken();
			HttpsClient client = new HttpsClient();
			String json = client.get("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo"
					+ "?access_token=" + accessToken
					+ "&code=" + code
					+ "&agentid=" + AGENT_ID);
			
			return getValueFromJson(json, JSONKEY_USERID);
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			throw new BusinessException(e,"连接微信服务器失败！");
		}
	}
	
}
